<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请人" prop="applicantName">
        <el-input
          v-model="queryParams.applicantName"
          placeholder="请输入申请人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报销金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入报销金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['operations:reimbursement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['operations:reimbursement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['operations:reimbursement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['operations:reimbursement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reimbursementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请人" align="center" prop="applicantName" width="100"/>
      <el-table-column label="费用类型" align="center" prop="expenseType" width="120"/>
      <el-table-column label="报销金额" align="center" prop="amount" width="120">
        <template slot-scope="scope">
          ¥{{ scope.row.amount ? scope.row.amount.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <el-table-column label="费用说明" align="center" prop="description" show-overflow-tooltip/>
      <el-table-column label="报销凭证" align="center" prop="images" width="100">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.images"
            size="mini"
            type="text"
            icon="el-icon-picture"
            @click="handlePreviewImages(scope.row.images)"
          >查看</el-button>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="财务审核人" align="center" prop="financeReviewerName" width="100"/>
      <el-table-column label="Admin审核人" align="center" prop="adminReviewerName" width="100"/>
      <el-table-column label="拒绝原因" align="center" prop="rejectReason" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <!-- 财务审核按钮：状态为待财务审核(1) 且 当前用户是财务角色 -->
          <el-button
            v-if="checkStatus(scope.row.status, 1) && isFinanceRole"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleFinanceReview(scope.row)"
          >财务审核</el-button>
          <!-- Admin审核按钮：状态为待Admin审核(2) 且 当前用户是Admin角色 -->
          <el-button
            v-if="checkStatus(scope.row.status, 2) && isAdminRole"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAdminReview(scope.row)"
          >Admin审核</el-button>
          <!-- 标记付款按钮：状态为审核通过待付款(5) 且 当前用户是财务或Admin角色 -->
          <el-button
            v-if="checkStatus(scope.row.status, 5) && (isFinanceRole || isAdminRole)"
            size="mini"
            type="text"
            icon="el-icon-money"
            @click="handleMarkPaid(scope.row)"
          >标记付款</el-button>
          <!-- 修改按钮：状态为草稿、待财务审核、财务拒绝、Admin拒绝 且 是申请人本人 -->
          <el-button
            v-if="canEdit(scope.row)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <!-- 查看详情按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
          >查看</el-button>
          <!-- 删除按钮：只有申请人本人或Admin可以删除 -->
          <el-button
            v-if="canDelete(scope.row)"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报销申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="申请人" prop="applicantId">
          <!-- 财务角色：可选择申请人 -->
          <el-select 
            v-if="isFinanceRole && !isViewMode" 
            v-model="form.applicantId" 
            placeholder="请选择申请人" 
            style="width: 100%"
            filterable
            @change="handleApplicantChange"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.value"
              :label="user.label"
              :value="user.value"
            ></el-option>
          </el-select>
          <!-- 非财务角色或查看模式：显示申请人姓名（禁用） -->
          <el-input 
            v-else
            v-model="form.applicantName" 
            disabled 
            :placeholder="title === '添加报销申请' ? currentUserName : ''"
          />
        </el-form-item>
        <el-form-item label="费用类型" prop="expenseType">
          <el-select v-model="form.expenseType" placeholder="请选择费用类型" style="width: 100%" :disabled="isViewMode">
            <el-option
              v-for="dict in dict.type.finance_expense_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报销金额" prop="amount">
          <el-input-number 
            v-model="form.amount" 
            :min="0" 
            :precision="2" 
            :step="100" 
            controls-position="right"
            style="width: 100%"
            placeholder="请输入报销金额"
            :disabled="isViewMode"
          />
        </el-form-item>
        <el-form-item label="费用说明" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入费用说明" :disabled="isViewMode"/>
        </el-form-item>
        <el-form-item label="报销凭证">
          <div v-if="isViewMode && form.images">
            <el-button size="small" type="primary" icon="el-icon-picture" @click="handlePreviewImages(form.images)">查看凭证</el-button>
          </div>
          <el-upload
            v-else
            ref="imageUpload"
            :action="imageUpload.url"
            :headers="imageUpload.headers"
            :file-list="imageUpload.fileList"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :on-remove="handleImageRemove"
            list-type="picture-card"
            multiple
            accept="image/*"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">支持jpg/png格式，单个文件不超过40MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            ref="upload"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="true"
            :disabled="isViewMode"
            multiple
          >
            <el-button size="small" type="primary" :disabled="isViewMode">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">可上传多个文件，单个不超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注信息" :disabled="isViewMode"/>
        </el-form-item>
        <!-- 拒绝原因展示（编辑被拒绝的申请时显示） -->
        <el-form-item label="拒绝原因" v-if="!isViewMode && (form.status === 3 || form.status === 4) && form.rejectReason">
          <el-alert
            :title="form.status === 3 ? '财务拒绝原因' : 'Admin拒绝原因'"
            type="error"
            :description="form.rejectReason"
            :closable="false"
            show-icon>
          </el-alert>
        </el-form-item>
        <!-- 审核信息展示 -->
        <div v-if="isViewMode && form.status > 1">
          <el-divider>审核信息</el-divider>
          <el-form-item label="财务审核人" v-if="form.financeReviewerName">
            <el-input v-model="form.financeReviewerName" disabled/>
          </el-form-item>
          <el-form-item label="财务审核时间" v-if="form.financeReviewTime">
            <el-input v-model="form.financeReviewTime" disabled/>
          </el-form-item>
          <el-form-item label="财务审核备注" v-if="form.financeReviewRemark">
            <el-input v-model="form.financeReviewRemark" type="textarea" :rows="2" disabled/>
          </el-form-item>
          <el-form-item label="Admin审核人" v-if="form.adminReviewerName">
            <el-input v-model="form.adminReviewerName" disabled/>
          </el-form-item>
          <el-form-item label="Admin审核时间" v-if="form.adminReviewTime">
            <el-input v-model="form.adminReviewTime" disabled/>
          </el-form-item>
          <el-form-item label="Admin审核备注" v-if="form.adminReviewRemark">
            <el-input v-model="form.adminReviewRemark" type="textarea" :rows="2" disabled/>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!isViewMode">确 定</el-button>
        <el-button @click="cancel">{{ isViewMode ? '关 闭' : '取 消' }}</el-button>
      </div>
    </el-dialog>

    <!-- 财务审核对话框 -->
    <el-dialog title="财务审核" :visible.sync="financeReviewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请人">{{ reviewForm.applicantName }}</el-descriptions-item>
        <el-descriptions-item label="费用类型">{{ reviewForm.expenseType }}</el-descriptions-item>
        <el-descriptions-item label="报销金额">
          <span style="color: #f56c6c; font-weight: bold;">¥{{ reviewForm.amount ? reviewForm.amount.toFixed(2) : '0.00' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ reviewForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="费用说明" :span="2">{{ reviewForm.description }}</el-descriptions-item>
        <el-descriptions-item label="报销凭证" :span="2" v-if="reviewForm.images">
          <el-button size="mini" type="primary" icon="el-icon-picture" @click="handlePreviewImages(reviewForm.images)">查看凭证</el-button>
        </el-descriptions-item>
      </el-descriptions>
      <el-divider></el-divider>
      <el-form ref="financeReviewForm" :model="reviewForm" label-width="100px">
        <el-form-item label="审核结果" required>
          <el-radio-group v-model="reviewForm.financeReviewStatus">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input v-model="reviewForm.financeReviewRemark" type="textarea" :rows="3" placeholder="请输入审核意见（拒绝时必填）" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFinanceReview">确 定</el-button>
        <el-button @click="financeReviewOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- Admin审核对话框 -->
    <el-dialog title="Admin审核" :visible.sync="adminReviewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请人">{{ reviewForm.applicantName }}</el-descriptions-item>
        <el-descriptions-item label="费用类型">{{ reviewForm.expenseType }}</el-descriptions-item>
        <el-descriptions-item label="报销金额">
          <span style="color: #f56c6c; font-weight: bold;">¥{{ reviewForm.amount ? reviewForm.amount.toFixed(2) : '0.00' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ reviewForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="费用说明" :span="2">{{ reviewForm.description }}</el-descriptions-item>
        <el-descriptions-item label="报销凭证" :span="2" v-if="reviewForm.images">
          <el-button size="mini" type="primary" icon="el-icon-picture" @click="handlePreviewImages(reviewForm.images)">查看凭证</el-button>
        </el-descriptions-item>
        <el-descriptions-item label="财务审核人">{{ reviewForm.financeReviewerName }}</el-descriptions-item>
        <el-descriptions-item label="财务审核时间">{{ reviewForm.financeReviewTime }}</el-descriptions-item>
        <el-descriptions-item label="财务审核意见" :span="2">{{ reviewForm.financeReviewRemark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <el-divider></el-divider>
      <el-form ref="adminReviewForm" :model="reviewForm" label-width="100px">
        <el-form-item label="审核结果" required>
          <el-radio-group v-model="reviewForm.adminReviewStatus">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input v-model="reviewForm.adminReviewRemark" type="textarea" :rows="3" placeholder="请输入审核意见（拒绝时必填）" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdminReview">确 定</el-button>
        <el-button @click="adminReviewOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog title="报销凭证预览" :visible.sync="imagePreviewOpen" width="800px" append-to-body>
      <div class="image-preview-container">
        <el-image
          v-for="(url, index) in previewImageList"
          :key="index"
          :src="url"
          :preview-src-list="previewImageList"
          fit="contain"
          style="width: 200px; height: 200px; margin: 10px;"
        ></el-image>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReimbursement, getReimbursement, delReimbursement, addReimbursement, updateReimbursement, financeReview, adminReview, markPaid } from "@/api/operations/reimbursement"
import { listUser } from "@/api/system/user"
import { getToken } from "@/utils/auth"
import { download } from '@/utils/download';

export default {
  name: "Reimbursement",
  dicts: ['finance_expense_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报销申请表格数据
      reimbursementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前用户名
      currentUserName: '',
      // 图片上传参数
      imageUpload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/operations/reimbursement/uploadImage",
        // 上传的文件列表
        fileList: []
      },
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/operations/reimbursement/upload",
        // 上传的文件列表
        fileList: []
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicantName: null,
        expenseType: null,
        amount: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        applicantId: [
          { required: true, message: "申请人不能为空", trigger: "change" }
        ],
        expenseType: [
          { required: true, message: "费用类型不能为空", trigger: "change" }
        ],
        amount: [
          { required: true, message: "报销金额不能为空", trigger: "blur" }
        ],
        description: [
          { required: true, message: "费用说明不能为空", trigger: "blur" }
        ],
      },
      // 报销状态选项
      statusOptions: [
        { value: 0, label: '草稿' },
        { value: 1, label: '待财务审核' },
        { value: 2, label: '待Admin审核' },
        { value: 3, label: '财务审核拒绝' },
        { value: 4, label: 'Admin审核拒绝' },
        { value: 5, label: '审核通过待付款' },
        { value: 6, label: '已付款' }
      ],
      // 财务审核对话框
      financeReviewOpen: false,
      // Admin审核对话框
      adminReviewOpen: false,
      // 审核表单
      reviewForm: {
        id: null,
        financeReviewStatus: null,
        financeReviewRemark: '',
        adminReviewStatus: null,
        adminReviewRemark: ''
      },
      // 图片预览
      imagePreviewOpen: false,
      previewImageList: [],
      // 是否为查看模式
      isViewMode: false,
      // 用户列表（用于财务角色选择申请人）
      userOptions: []
    }
  },
  created() {
    this.getList()
    this.currentUserName = this.$store.getters.name
    // 如果是财务角色，加载用户列表
    if (this.isFinanceRole) {
      this.getUserList()
    }
  },
  computed: {
    // 获取当前用户角色
    currentUserRoles() {
      return this.$store.getters.roles || []
    },
    // 判断是否为财务角色
    isFinanceRole() {
      return this.currentUserRoles.includes('财务')
    },
    // 判断是否为Admin角色
    isAdminRole() {
      return this.currentUserRoles.includes('admin')
    }
  },
  methods: {
    /** 查询报销申请列表 */
    getList() {
      this.loading = true
      listReimbursement(this.queryParams).then(response => {
        this.reimbursementList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取用户列表（财务角色使用） */
    getUserList() {
      listUser({ pageNum: 1, pageSize: 9999 }).then(response => {
        this.userOptions = response.rows.map(user => ({
          value: user.userId,
          label: `${user.nickName} (${user.userName})`,
          userName: user.userName
        }))
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        applicantId: null,
        expenseType: null,
        amount: null,
        description: null,
        attachment: null,
        images: null,
        status: null,
        rejectReason: null,
        paymentId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.imageUpload.fileList = []
      this.upload.fileList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 如果不是财务角色，自动设置申请人为当前用户
      if (!this.isFinanceRole) {
        this.form.applicantName = this.currentUserName
        this.form.applicantId = this.$store.getters.id
      }
      this.isViewMode = false
      this.open = true
      this.title = "添加报销申请"
    },
    /** 申请人选择变化处理（财务角色使用） */
    handleApplicantChange(userId) {
      const selectedUser = this.userOptions.find(user => user.value === userId)
      if (selectedUser) {
        this.form.applicantName = selectedUser.userName
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getReimbursement(id).then(response => {
        this.form = response.data
        
        // 判断是查看还是修改
        // 状态为草稿(0)、待财务审核(1)、财务拒绝(3)、Admin拒绝(4)，且是申请人本人，才能修改
        const currentUserId = this.$store.getters.id  // 修正：使用 id 而不是 userId
        const canEdit = (this.form.status === 0 || this.form.status === 1 || this.form.status === 3 || this.form.status === 4) && this.form.applicantId === currentUserId
        this.isViewMode = !canEdit
        
        // 处理图片列表
        if (this.form.images) {
          this.imageUpload.fileList = this.form.images.split(',').map((url, index) => {
            return {
              name: 'image_' + index,
              url: url
            }
          })
        }
        
        // 处理附件列表
        if (this.form.attachment) {
          this.upload.fileList = this.form.attachment.split(',').map((url, index) => {
            return {
              name: url.substring(url.lastIndexOf('/') + 1),
              url: url
            }
          })
        }
        
        this.open = true
        this.title = this.isViewMode ? "查看报销申请" : "修改报销申请"
      })
    },
    /** 图片上传成功处理 */
    handleImageSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 收集所有已上传图片的URL（包括已有的和新上传的）
        const imageUrls = fileList
          .filter(f => (f.response && f.response.code === 200) || f.url)
          .map(f => f.response ? f.response.url : f.url)
        this.form.images = imageUrls.join(',')
        this.$modal.msgSuccess("图片上传成功");
      } else {
        this.$modal.msgError(response.msg || "图片上传失败");
        // 移除上传失败的文件
        const index = fileList.indexOf(file)
        if (index > -1) {
          fileList.splice(index, 1)
        }
      }
    },
    /** 图片上传前校验 */
    beforeImageUpload(file) {
      const isImage = file.type.indexOf('image/') === 0
      const isLt200M = file.size / 1024 / 1024 < 200

      if (!isImage) {
        this.$modal.msgError('只能上传图片文件!')
        return false
      }
      if (!isLt200M) {
        this.$modal.msgError('图片大小不能超过 200MB!')
        return false
      }
      return true
    },
    /** 图片移除处理 */
    handleImageRemove(file, fileList) {
      // 重新收集剩余图片的URL（包括已有的和新上传的）
      const imageUrls = fileList
        .filter(f => (f.response && f.response.code === 200) || f.url)
        .map(f => f.response ? f.response.url : f.url)
      this.form.images = imageUrls.length > 0 ? imageUrls.join(',') : null
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      if (response.code === 200) {
        if (this.form.attachment) {
          this.form.attachment += ',' + response.url; 
        } else {
          this.form.attachment = response.url; 
        }
        this.$modal.msgSuccess("上传成功");
      } else {
        this.$modal.msgError(response.msg || "上传失败");
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateReimbursement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addReimbursement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除报销申请编号为"' + ids + '"的数据项？').then(function() {
        return delReimbursement(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('operations/reimbursement/export', {
        ...this.queryParams
      }, `reimbursement_${new Date().getTime()}.xlsx`)
    },
    /** 财务审核 */
    handleFinanceReview(row) {
      // 获取完整的报销信息
      getReimbursement(row.id).then(response => {
        this.reviewForm = {
          ...response.data,
          financeReviewStatus: null,
          financeReviewRemark: ''
        }
        this.financeReviewOpen = true
      })
    },
    /** 提交财务审核 */
    submitFinanceReview() {
      if (this.reviewForm.financeReviewStatus === null) {
        this.$modal.msgWarning("请选择审核结果")
        return
      }
      // 拒绝时必须填写备注
      if (this.reviewForm.financeReviewStatus === 2 && !this.reviewForm.financeReviewRemark) {
        this.$modal.msgWarning("拒绝时必须填写审核备注")
        return
      }
      financeReview(this.reviewForm).then(response => {
        this.$modal.msgSuccess("审核成功")
        this.financeReviewOpen = false
        this.getList()
      })
    },
    /** Admin审核 */
    handleAdminReview(row) {
      // 获取完整的报销信息
      getReimbursement(row.id).then(response => {
        this.reviewForm = {
          ...response.data,
          adminReviewStatus: null,
          adminReviewRemark: ''
        }
        this.adminReviewOpen = true
      })
    },
    /** 提交Admin审核 */
    submitAdminReview() {
      if (this.reviewForm.adminReviewStatus === null) {
        this.$modal.msgWarning("请选择审核结果")
        return
      }
      // 拒绝时必须填写备注
      if (this.reviewForm.adminReviewStatus === 2 && !this.reviewForm.adminReviewRemark) {
        this.$modal.msgWarning("拒绝时必须填写审核备注")
        return
      }
      adminReview(this.reviewForm).then(response => {
        this.$modal.msgSuccess("审核成功")
        this.adminReviewOpen = false
        this.getList()
      })
    },
    /** 标记为已付款 */
    handleMarkPaid(row) {
      this.$modal.confirm('确认将该报销申请标记为已付款吗？').then(() => {
        return markPaid(row.id)
      }).then(() => {
        this.$modal.msgSuccess("标记成功")
        this.getList()
      }).catch(() => {})
    },
    /** 预览图片 */
    handlePreviewImages(images) {
      if (images) {
        this.previewImageList = images.split(',')
        this.imagePreviewOpen = true
      }
    },
    /** 获取状态标签 */
    getStatusLabel(status) {
      const option = this.statusOptions.find(item => item.value === status)
      return option ? option.label : '未知'
    },
    /** 获取状态类型 */
    getStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'warning',
        3: 'danger',
        4: 'danger',
        5: 'success',
        6: 'success'
      }
      return typeMap[status] || 'info'
    },
    /** 检查状态 - 兼容字符串和数字 */
    checkStatus(status, targetStatus) {
      // 将状态统一转换为数字进行比较
      return Number(status) === Number(targetStatus)
    },
    /** 判断是否可以编辑 */
    canEdit(row) {
      const currentUserId = this.$store.getters.id  // 修正：使用 id 而不是 userId
      const status = Number(row.status)
      const applicantId = Number(row.applicantId)
      
      // 状态为草稿(0)、待财务审核(1)、财务拒绝(3)、Admin拒绝(4)，且是申请人本人
      const canEditStatus = [0, 1, 3, 4].includes(status)
      const isOwner = applicantId === currentUserId
      
      return canEditStatus && isOwner
    },
    /** 判断是否可以删除 */
    canDelete(row) {
      const currentUserId = this.$store.getters.id  // 修正：使用 id 而不是 userId
      const applicantId = Number(row.applicantId)
      
      // 申请人本人或Admin角色可以删除
      return applicantId === currentUserId || this.isAdminRole
    }
  }
}
</script>

<style scoped>
.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
</style>
